var express = require('express');
var router = express.Router();
var mongo = require("./db")
var mongodb = require("mongodb");
const e = require('express');
var ObjectId = mongodb.ObjectId;
/* GET home page. */
router.get('/', function (req, res, next) {
  // res.render('index', { title: 'Express' });
});
// 添加商品接口
router.post("/add", function (req, res) {
  var obj = {
    goodsname: req.body.goodsname,
    price: req.body.price,
    num: req.body.num
  }
  mongo("insert", "list", obj, function () {
    res.send({ success: "添加成功" })
  })
})
// 查询列表接口
router.get("/all", function (req, res) {
  mongo("find", "list", {}, function (data) {
    res.send(data)
  })
})
// 删除接口
router.get("/del", function (req, res) {
  mongo("del", "list", { _id: ObjectId(req.query._id) }, function () {
    res.send({ success: "删除成功" })
  })
})
// 排序接口
// router.post("/sortPrice", function (req, res) {
//   var len = 0;
//   mongo("sortFind", "list", {}, function (data) {
//     len = data.length;
//     res.send(data);
//   }, {
//     price: Number(req.body.order)
//   }, 0, len) //排序条件
// })
router.post("/sortPrice", function (req, res) {
  var len = 0;
  mongo("find", "list", {}, function (data) {
    len = data.length;
    if (req.body.order == 1) {
      data.sort(function (a, b) {
        return a.price - b.price
      })
    } else {
      data.sort(function (a, b) {
        return b.price - a.price
      })
    }
    res.send(data);
  })
})

// 分页查询接口
router.post("/pageList", function (req, res) {
  var skip = 3 * Number(req.body.page) - 3;
  var len = 0;
  mongo("sortFind", "list", {}, function (data) {
    mongo("find", "list", {}, function (mydata) {
      res.send({
        data: data,
        pageSize: Number(req.body.pageSize),
        count: mydata.length
      })
    })
  }, {}, skip, Number(req.body.pageSize))
})



module.exports = router;
